<?php
namespace Common\Model;
use Think\Model;
class AllMsgModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_all_msg'; 
	
	public function addMsg($data){
		$result = $this->add($data);
		return $result;
	}
	
	
	public function getMsgList($data){
		$whereStr = "";
		if(!empty($data['fromcustid']) && !empty($data['tocustid'])){
			$whereStr = "(fromcustid={$data['fromcustid']} and tocustid={$data['tocustid']}) or (fromcustid={$data['tocustid']} and tocustid={$data['fromcustid']})";
		}
	
		if(!empty($data['datemin'])){
			$datemin = strtotime($data['datemin']);
			$whereStr = $whereStr . " and msgtime>={$datemin}";
			
		}
		
		if(!empty($data['datemax'])){
			$datemax = strtotime($data['datemax'])+86400;
			$whereStr = $whereStr . " and msgtime<={$datemax}";
		}
		
		//echo $whereStr;
		
		$total = $this->where($whereStr)->count();
		$fields = array('id','chatid','chattype','fromcustid','tocustid','msgid',
				'msgno','msgtype','msgtime','logintype','msgexpiretime','content','createtime','updatetime');
	
		if(empty($data['sortField']))$data['sortField'] = "msgtime";
		if(empty($data['sortOrder']))$data['sortOrder'] = "desc";
	
		if(empty($data['pageSize']) && empty($data['pageIndex']))
			$result = $this->field($fields)->where($whereStr)->order("{$data['sortField']} {$data['sortOrder']}")->select();
		else
			$result = $this->field($fields)->where($whereStr)->order("{$data['sortField']} {$data['sortOrder']}")->limit($data['pageIndex']*$data['pageSize'] , $data['pageSize'])->select();
	
		$pages = !empty($data['pageSize']) ? ceil($total/$data['pageSize']) : 1;
		
		return array('total'=>$total , 'data'=>$result , 'pages'=>$pages);
	}
	
}


